<template>
  <div class="forgot-password-container">
    <div class="forgot-password-box">
      <div class="forgot-password-header">
        <img src="../assets/logo.png" alt="Logo" class="logo" />
        <h1>重置密码</h1>
      </div>

      <!-- 步骤1: 输入邮箱和验证码 -->
      <el-form
          v-if="currentStep === 1"
          :model="emailForm"
          :rules="emailFormRules"
          ref="emailFormRef"
          class="forgot-password-form"
      >
        <el-form-item prop="email">
          <el-input
              v-model="emailForm.email"
              placeholder="请输入注册邮箱"
              :prefix-icon="Message"
              size="large"
              class="forgot-password-input"
          />
        </el-form-item>

        <el-form-item prop="captcha" class="captcha-item">
          <el-input
              v-model="emailForm.captcha"
              placeholder="验证码"
              :prefix-icon="Key"
              maxlength="5"
              size="large"
              class="captcha-input"
          />
          <img
              :src="captchaImage"
              class="captcha-image"
              @click="loadCaptcha"
              alt="验证码"
          />
        </el-form-item>

        <el-form-item>
          <el-button
              class="submit-button"
              type="primary"
              @click="sendVerificationCode"
              size="large"
              :loading="sendingCode"
          >
            {{ sendingCode ? '发送中...' : '发送验证码' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 步骤2: 输入邮箱验证码 -->
      <el-form
          v-if="currentStep === 2"
          :model="verificationForm"
          :rules="verificationFormRules"
          ref="verificationFormRef"
          class="forgot-password-form"
      >
        <div class="step-info">
          验证码已发送至您的邮箱 {{ maskedEmail }}，请查收
        </div>

        <el-form-item prop="code">
          <el-input
              v-model="verificationForm.code"
              placeholder="请输入邮箱验证码"
              :prefix-icon="Lock"
              maxlength="4"
              size="large"
              class="forgot-password-input"
          />
        </el-form-item>

        <el-form-item>
          <el-button
              class="submit-button"
              type="primary"
              @click="verifyCode"
              size="large"
          >
            验证
          </el-button>
        </el-form-item>

        <div class="resend-section">
          <span v-if="countdown > 0">重新发送 ({{ countdown }}s)</span>
          <el-button
              v-else
              type="text"
              @click="resendCode"
              class="resend-button"
          >
            重新发送验证码
          </el-button>
        </div>
      </el-form>

      <!-- 步骤3: 重置密码 -->
      <el-form
          v-if="currentStep === 3"
          :model="resetForm"
          :rules="resetFormRules"
          ref="resetFormRef"
          class="forgot-password-form"
      >
        <el-form-item prop="password">
          <el-input
              v-model="resetForm.password"
              placeholder="请输入新密码"
              show-password
              :prefix-icon="Lock"
              size="large"
              class="forgot-password-input"
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
              v-model="resetForm.confirmPassword"
              placeholder="请确认新密码"
              show-password
              :prefix-icon="Lock"
              size="large"
              class="forgot-password-input"
          />
        </el-form-item>

        <el-form-item>
          <el-button
              class="submit-button"
              type="primary"
              @click="resetPassword"
              size="large"
              :loading="resettingPassword"
          >
            {{ resettingPassword ? '重置中...' : '重置密码' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 完成页面 -->
      <div v-if="currentStep === 4" class="success-section">
        <div class="success-icon">
          <el-icon class="success-check"><Check /></el-icon>
        </div>
        <h2>密码重置成功</h2>
        <p>您的密码已成功重置，现在可以使用新密码登录。</p>
        <el-button
            class="login-button"
            type="primary"
            @click="goToLogin"
            size="large"
        >
          返回登录
        </el-button>
      </div>

      <div class="back-to-login">
        <el-button
            type="text"
            @click="goToLogin"
            class="back-button"
        >
          <el-icon><ArrowLeft /></el-icon> 返回登录
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Message, Key, Lock, ArrowLeft, Check } from '@element-plus/icons-vue'
import loginApi from '../api/login_api.js'

const router = useRouter()

// 当前步骤：1-输入邮箱，2-输入邮箱验证码，3-重置密码，4-完成
const currentStep = ref(1)

// 邮箱表单
const emailForm = reactive({
  email: '',
  captcha: '',
  key: ''
})

// 邮箱表单验证规则
const emailFormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 验证码表单
const verificationForm = reactive({
  code: ''
})

// 验证码表单验证规则
const verificationFormRules = {
  code: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '验证码为4位数字', trigger: 'blur' }
  ]
}

// 重置密码表单
const resetForm = reactive({
  password: '',
  confirmPassword: ''
})

// 重置密码表单验证规则
const resetFormRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 验证确认密码
function validateConfirmPassword(rule, value, callback) {
  if (value !== resetForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 验证码图片
const captchaImage = ref('')

// 发送验证码按钮状态
const sendingCode = ref(false)

// 重置密码按钮状态
const resettingPassword = ref(false)

// 倒计时
const countdown = ref(0)
let countdownTimer = null

// 掩码邮箱显示
const maskedEmail = ref('')

// 表单引用
const emailFormRef = ref(null)
const verificationFormRef = ref(null)
const resetFormRef = ref(null)

// 加载验证码
const loadCaptcha = async () => {
  try {
    const res = await loginApi.captcha()
    emailForm.key = res.key
    captchaImage.value = res.base
  } catch (error) {
    ElMessage.error('验证码加载失败')
  }
}

// 发送邮箱验证码
const sendVerificationCode = async () => {
  if (!emailFormRef.value) return

  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      sendingCode.value = true
      try {
        // 调用后端发送验证码接口
        const res = await loginApi.sendResetCode({
          email: emailForm.email,
          captcha: emailForm.captcha,
          key: emailForm.key
        })

        if (res) {
          ElMessage.success('验证码已发送至您的邮箱')
          currentStep.value = 2
          maskedEmail.value = maskEmail(emailForm.email)

          // 开始倒计时
          startCountdown(60)
        }
      } catch (error) {
        ElMessage.error(error.message || '发送验证码失败')
        // 重新加载验证码
        loadCaptcha()
      } finally {
        sendingCode.value = false
      }
    }
  })
}

// 验证邮箱验证码
const verifyCode = async () => {
  if (!verificationFormRef.value) return

  await verificationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用后端验证接口
        const res = await loginApi.verifyResetCode({
          email: emailForm.email,
          code: verificationForm.code
        })

        if (res) {
          ElMessage.success('验证成功')
          currentStep.value = 3
          // 清除倒计时
          if (countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
          }
        }
      } catch (error) {
        ElMessage.error(error.message || '验证码验证失败')
      }
    }
  })
}

// 重置密码
const resetPassword = async () => {
  if (!resetFormRef.value) return

  await resetFormRef.value.validate(async (valid) => {
    if (valid) {
      resettingPassword.value = true
      try {
        // 调用后端重置密码接口
        const res = await loginApi.resetPasswordByEmail({
          email: emailForm.email,
          password: resetForm.password
        })

        if (res) {
          ElMessage.success('密码重置成功')
          currentStep.value = 4
        }
      } catch (error) {
        ElMessage.error(error.message || '密码重置失败')
      } finally {
        resettingPassword.value = false
      }
    }
  })
}

// 开始倒计时
const startCountdown = (seconds) => {
  countdown.value = seconds
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)
}

// 重新发送验证码
const resendCode = async () => {
  try {
    // 重新加载验证码
    await loadCaptcha()
    ElMessage.info('请重新输入验证码')
    currentStep.value = 1
  } catch (error) {
    ElMessage.error('重新发送失败')
  }
}

// 返回登录页面
const goToLogin = () => {
  router.push('/login')
}

// 邮箱掩码处理
const maskEmail = (email) => {
  if (!email) return ''
  const [name, domain] = email.split('@')
  if (name.length <= 2) {
    return email
  }
  const maskedName = name.charAt(0) + '*'.repeat(name.length - 2) + name.charAt(name.length - 1)
  return `${maskedName}@${domain}`
}

// 组件挂载时加载验证码
onMounted(() => {
  loadCaptcha()
})

// 组件卸载时清除定时器
// eslint-disable-next-line no-unused-vars
onMounted(() => {
  return () => {
    if (countdownTimer) {
      clearInterval(countdownTimer)
    }
  }
})
</script>

<style scoped>
.forgot-password-container {
  min-height: 100vh;
  background-image: url('../assets/background.png');
  background-size: cover; /* 让图片铺满容器 */
  background-position: center; /* 图片居中 */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.forgot-password-box {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  border: 1px solid #e1edff;
}

.forgot-password-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
}

.forgot-password-header h1 {
  color: #333;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.forgot-password-form {
  margin-top: 20px;
}

.forgot-password-input {
  width: 100%;
}

:deep(.forgot-password-input .el-input__wrapper) {
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: none;
}

:deep(.forgot-password-input .el-input__inner) {
  color: #606266;
  background: transparent;
}

:deep(.forgot-password-input .el-input__inner::placeholder) {
  color: #c0c4cc;
}

.captcha-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 100px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  background: #fff;
}

.step-info {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
  text-align: center;
}

.submit-button {
  width: 100%;
  background: linear-gradient(90deg, #0e88eb 0%, #1a9fff 100%);
  border: none;
  font-weight: 600;
  letter-spacing: 1px;
  margin-top: 10px;
  color: white;
}

.submit-button:hover {
  background: linear-gradient(90deg, #1a9fff 0%, #0e88eb 100%);
  transform: translateY(-2px);
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(14, 136, 235, 0.3);
}

.resend-section {
  text-align: center;
  margin-top: 15px;
  color: #666;
  font-size: 14px;
}

.resend-button {
  color: #0e88eb;
  font-weight: 600;
  margin-left: 5px;
}

.resend-button:hover {
  color: #1a9fff;
  text-decoration: underline;
}

.success-section {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  margin-bottom: 20px;
}

.success-check {
  font-size: 48px;
  color: #0e88eb;
  background: rgba(14, 136, 235, 0.1);
  border-radius: 50%;
  padding: 20px;
}

.success-section h2 {
  color: #333;
  margin-bottom: 10px;
}

.success-section p {
  color: #666;
  margin-bottom: 30px;
}

.login-button {
  width: 100%;
  background: linear-gradient(90deg, #0e88eb 0%, #1a9fff 100%);
  border: none;
  font-weight: 600;
  letter-spacing: 1px;
  color: white;
}

.login-button:hover {
  background: linear-gradient(90deg, #1a9fff 0%, #0e88eb 100%);
  transform: translateY(-2px);
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(14, 136, 235, 0.3);
}

.back-to-login {
  text-align: center;
  margin-top: 20px;
}

.back-button {
  color: #0e88eb;
  font-weight: 600;
}

.back-button:hover {
  color: #1a9fff;
  text-decoration: underline;
}

@media (max-width: 480px) {
  .forgot-password-box {
    padding: 20px;
  }

  .captcha-item {
    flex-direction: column;
    align-items: stretch;
  }

  .captcha-image {
    width: 100%;
    margin-top: 10px;
  }
}
</style>
